from django.shortcuts import render

from django.http import HttpResponse,JsonResponse

from django.contrib.auth.hashers import make_password, check_password

from myadmin.models import *

from django.core.urlresolvers import reverse


# 地址添加
def addressinsert(request):
    # 接收数据
    data=request.GET.dict()
    # 获取用户对象
    data['uid']=Users.objects.get(id=request.session['VipUser']['uid'])
    # 判断是否为默认
    if data['status']=='1':
        data['status']=True
        # 把其他的地址改为默认
        obs=Address.objects.filter(uid=data['uid'])
        for x in obs:
            x.status=False
            x.save()
    # 执行添加
    ob=Address.objects.create(**data)
    # 返回数据
    return  JsonResponse({'error':0,'msg':'地址添加成功'})

# 地址管理
def myaddress(request):
    # 获取当前用户对象的信息
    ob=Address.objects.filter(uid=request.session['VipUser']['uid'])
    # print(ob)
    # 分配数据
    context={'ob':ob}
    # 加载魔板
    return render(request,'myhome/center/myaddress.html',context)

# 地址删除
def addressdelete(request):
    # 接受id,获取对象
    uid=request.GET['id']
    # 获取数据
    ob = Address.objects.get(id=uid)
    ob.delete()  
    # 返回信息
    return JsonResponse({'error':0,'msg':'删除成功'})

# 地址修改
def addressedit(request):
    # 接受id,获取对象
    dict1={}
    uid=request.GET['id']
    print(uid)
    # 获取数据
    ob = Address.objects.get(id=uid)
    dict1['addressname']=ob.addressname
    dict1['address']=ob.address
    dict1['addressphone']=ob.addressphone
    dict1['id']=ob.id
    dict1['status']=ob.status
    print(dict1)
    # 返回信息
    return JsonResponse(dict1)

# 地址更新
def addressupdate(request):
    # # 接收数据
    # data=request.GET.dict()
    # # print(data)
    # # if data['status']=='1':
    # #     data['status']=True
    # # else:
    # #     data['status']=False
    # # 获取用户对象
    # aid=int(data['aid'])
    # ob = Address.objects.get(id=aid)
    # # 更新数据
    # ob.address=data['address']
    # ob.addressname=data['addressname']
    # ob.addressphone=data['addressphone']
    # ob.status=data['status']
    # # 执行
    # ob.save()
    # return HttpResponse('hahahha')
    data=request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    print(data)
    ob=Address.objects.get(id=data['id'])
    ob.addressname=data['addressname']
    ob.address=data['address']
    ob.addressphone=data['addressphone']
    obs=Address.objects.filter(uid=request.session['VipUser']['uid'])
    if 'status' in data.keys():
        for i in obs:
            i.status=False
            i.save()
        ob.status=True
    ob.save()        
    return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myhome_myaddress')+'"</script>')


    


    
# -----------------------------------------------------------

# Create your views here.

# -----------------------------------------------------------

# 首页
def index(request):
    
    # 获取所有的二级分类
    erlist = Types.objects.exclude(pid=0)

    context = {'erlist':erlist}

    # 获取所有的一级分类
    data = Types.objects.filter(pid=0)
    for x in data:
        x.items = Types.objects.filter(pid=x.id)

    context['tlist'] = data

    return render(request,'myhome/index.html',context)

# 列表页
def goodslist(request,tid):
    # 获取当前分类对象
    ob=Types.objects.get(id=tid)
    # 判断当前是一节分类还是二级分类
    if ob.pid==0:
        # 一级分类
        data=ob
        data.items=Types.objects.filter(pid=ob.id)
        ids=[]
        for x in data.items:
            ids.append(x.id)
        # 获取所有子类的商品
        data.goodslist=Goods.objects.filter(tid__in=ids)
    else:
        # 二级分类
        # 先获取当前类的父类
        data=Types.objects.get(id=ob.pid)
        # 获取当前类的子类
        data.items=Types.objects.filter(pid=data.id)
        # 获取当前二级类的商品
        data.goodslist=Goods.objects.filter(tid=ob.id)

    # 分配数据
    context={'data':data,'ob':ob}
    # 加载魔板
    return render(request,'myhome/list.html',context)

# 详情页
def goodsinfo(request,gid):
    # 根据商品gid获取数据
    ob=Goods.objects.get(id=gid)
    # 分配数据
    context={'ob':ob}
    # 加载魔板
    return render(request,'myhome/info.html',context)


# ----------------------------------------------------------

# 登陆
def login(request):
    nextpath=request.GET.get('nextpath','/')
    # 判断当前请求状态
    if request.method=='POST':
        # 判断验证码是否正确
        if(request.POST['vcode']).upper()!=(request.session.get('verifycode')).upper():
            return HttpResponse('<script>alert("验证码错误");location.href="/login/"</script>')
        try:
            # 根据手机号获取用户
            ob=Users.objects.get(phone=request.POST['phone'])
            # 验证密码
            if check_password(request.POST['password'],ob.password):
                # 执行登陆
                request.session['VipUser']={'uid':ob.id,'username':ob.username,'phone':ob.phone,'status':ob.status}
                # print(session.dict())
                return HttpResponse('<script>alert("登陆成功!");location.href="'+nextpath+'"</script>')
        except:
            pass
        return HttpResponse('<script>alert("登陆失败,用户名或密码错误!");location.href="/login/"</script>')
    else:       
        return render(request,'myhome/login.html')

#退出登陆
def logout(request):
    # 删除session中的用户
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录成功");location.href="/"</script>')
 
# 注册
def register(request):
    # 判断当前的请求状态
    if request.method =='POST':
        #接受数据
        data=request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        data.pop('msgcode')
        print(data)
        # 判断手机号是否存在
        if Users.objects.filter(phone=data['phone']):
            return HttpResponse('<script>alert("该手机号已存在!请直接登陆");location.href="/login/"</script>')
        try:
            # 密码加密
            data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
            # # 是否上传头像
            # myfile=request.FILES.get('pic',None)
            # #判断是否有文件上传
            # if myfile:
            #     #有文件上传
            #     data['pic']=uploads(myfile)
            # else:
            #     # 没有文件上传
            #     data['pic']='/static/pics/user04.jpg'
            # 执行添加
            Users.objects.create(**data)
            # 跳转到登陆页
            return HttpResponse('<script>alert("注册成功,请登录");location.href="/login/"</script>')
        except:
            return HttpResponse('<script>alert("注册成功,请登录");location.href="/register/"</script>')
    else:   
        # 返回注册页面
        return render(request,'myhome/register.html')   

# 验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(),'image/png')

# 发送手机验证码
def sendmsg(request):

    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    #!/usr/local/bin/python
    #-*- coding:utf-8 -*-

    # import urllib2
    import urllib
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C17586531" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "f8a07bad8f75c0680c22d920f514c964"
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    # 把验证码存入session
    request.session['msgcode'] = code
    text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    req = urllib.request.urlopen(
        url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data= urllib.parse.urlencode(data).encode('utf-8')
    )
    content =req.read()
    res = json.loads(content.decode('utf-8'))
    print(res)
    return HttpResponse(res)



# ---------------------------------------------------------

# 购物车添加
def cartadd(request):
    # try:
        # 获取商品gid和num
        gid=request.GET['gid']
        # console.log(gid)
        num=int(request.GET['num'])
        print(num)
        # console.log(num)
        # 接收数据
        ob=Goods.objects.get(id=gid)
        # 准备数据
        goods={'gid':ob.id,'title':ob.title,'price':ob.price,'pic':ob.pic,'num':num}
        # 获取购物车数据
        data=request.session.get('Cart',{})
        # 判断当前选择的上坪是否已经存在购物车
        if gid in data:
            # {4:{}}
            # 存在,则修改数量
            data[gid]['num']+=num
        else:
            # 不存在,则添加
            data[gid]=goods
        # 重新存入购物车
        request.session['Cart']=data
        # 返回数据
        # return HttpResponse('cartadd')
        return JsonResponse({'error':0,'msg':'加入购物车成功!'})
    # except:
        # return JsonResponse({'error':1,'msg':'加入购物车失败!'})

# 购物车列表
def cartindex(request):
    # return HttpResponse('cartindex')
    return render(request,'myhome/cartindex.html')

# 购物车删除
def cartdelete(request,gid):
    # 获取购物车数据
    data=request.session.get('Cart',{})
    del data[gid]
    # 把修改好的购物车数据,重新存入session
    request.session['Cart']=data
    # 跳转页面
    return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')

# 购物车清空
def cartclear(request):
    # 直接讲session的cart变为空即可
    request.session['Cart']={}
    # 返回消息
    return HttpResponse('cartdelete')


# 购物车编辑
def cartedit(request):
    # # 获取商品gid和num
    # gid=request.GET.get('gid')
    # # console.log(gid)
    # num=int(request.GET.get('num'))
    # # 获取购物车数据
    # data=request.session['Cart']
    # # 修改商品购物数量
    # data[gid]['num']+=num
    # # 重新存入购物车
    # request.session['Cart']=data
    # # 页面跳转
    # # return HttpResponse('cartedit')
    # return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')
    gid = request.GET.get('gid')
    num = int(request.GET.get('num'))

    # 获取购物车数据
    data = request.session['Cart']
    # 修改商品购买数量
    data[gid]['num'] = num
    # 把购物车重新存入session
    request.session['Cart'] = data
    
    return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')

# ---------------------------------------------------------

# 订单确认
def orderconfirm(request):
    # 接受数据
    ids=request.GET.get('ids')
    ids=ids.split(',')
    # 购物车数据
    cart=request.session.get('Cart')
    data={}
    for x in ids:
        data[x]=cart[x]

    # 获取当前用户的所有收货地址
    adds=Address.objects.filter(uid=request.session['VipUser']['uid'])

    # 分配数据
    context = {'data':data,'adds':adds}

    # 加载魔板
    return render(request,'myhome/order/confirm.html',context)



# 订单生成
def ordercreate(request):

    # 接受数据 [1,2]
    ids=request.POST.get('ids')
    ids=ids.split(',')
    print(ids)
    addid=request.POST.get('addid')

    # 生成订单
    orderdata={}
    orderdata['uid']=Users.objects.get(id=request.session['VipUser']['uid'])
    orderdata['aid']=Address.objects.get(id=addid)
    orderdata['totalprice']=0
    ob=Order.objects.create(**orderdata)

    # 获取购物车数据
    cart=request.session['Cart']
    # print(cart,66666666666666)
    totalprice=0
    # 订单详情
    for x in ids:
        # 创建订单详情
        res=OrderInfo()
        res.orderid=ob
        goods=Goods.objects.get(id=x)
        res.goodsid=goods
        res.price=goods.price
        res.num=cart[x]['num']
        res.save()
        # 删除购物车中已购买的商品
        del cart[x]
        # 运算总价
        totalprice+=res.price*res.num
        # 扣库存
        goods.num-=res.num
        goods.save()

    # 购物车数据重新存入session
    request.session['Cart']=cart
    ob.totalprice=totalprice
    ob.save()

    # 跳转到支付页面
    return  HttpResponse('<script>alert("请支付");location.href="/order/buy/'+str(ob.id)+'/"</script>')

# 支付页面
def orderbuy(request,oid):
    # 根据订单id获取订单信息
    ob=Order.objects.get(id=oid)
    # 分配数据
    context={'order':ob}
    # 加载页面
    return render(request,'myhome/order/buy.html',context)

# 支付成功
def orderbuysuccess(request,oid):
    # 根据订单id获取订单详情
    ob=Order.objects.get(id=oid)
    # 修改状态
    ob.status=1
    # 保存
    ob.save()
    # 加载末班
    return render(request,'myhome/order/success.html')

# 我的订单
def myorder(request):
    # 获取当前用户对象的所有订单
    orderlist=Order.objects.filter(uid=request.session['VipUser']['uid'])
    # 分配数据
    context={'orderlist':orderlist}
    # 加载末班
    return render(request,'myhome/center/myorder.html',context)

# ---------------------------------------------------------

# 个人信息
def myselfset(request):
    # 获取当前用户对象的信息
    ob=Users.objects.get(id=request.session['VipUser']['uid'])
    # 分配数据
    context={'ob':ob}
    # 加载魔板
    return render(request,'myhome/center/myself.html',context)

# 文件上传的函数
def uploads(myfile):
    import time,random
    from web.settings import BASE_DIR

    filename = str(time.time())+str(random.randint(10000,99999))+'.'+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    return "/static/pics/"+filename

# 更新信息
def myupdate(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # print(data)

        # 获取对象
        ob = Users.objects.get(id=data['id'])
        ob.username = data['username']
        ob.email = data['email']
        ob.age = data['age']
        ob.sex = data['sex']

        # 是否上传头像--------------------------------------------有哟哟问题

        myfile=request.FILES.get('pic',None)
        print(myfile)
        #判断是否有文件上传
        if myfile:
            #有文件上传
            data['pic']=uploads(myfile)
            ob.pic=data['pic']

        # 判断是否右文件上传
        # myfile = request.FILES.get('pic',None)
        # if myfile:
        #     # 有新文件上传,删除原有的头像数据,
        #     # 判断是否使用的是默认头像
        #     if ob.pic != '/static/pics/user04.jpg':
        #         # 删除原来的头像
        #         os.remove(BASE_DIR+ob.pic)

        #     # 执行文件的上传.,并更新头像数据
        #     ob.pic = uploads(myfile)
        # 是否上传头像--------------------------------------------有哟哟问题

        # 执行更新
        ob.save()
        # 更新session的名字
        # request.session['VipUser']['username']=ob.username
        # 跳转页面
        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myhome_myselfset')+'"</script>')
    except:
        return HttpResponse('<script>alert("更新失败");location.href="'+reverse('myhome_myselfset')+'"</script>')

# ---------------------------------------------------------
